package cn.tedu.boot0201.controller;

import cn.tedu.boot0201.entity.Product;
import cn.tedu.boot0201.utils.DBUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@RestController
public class ProductController {

    @RequestMapping("/insert")
    public String insert(Product product){

        try (Connection conn = DBUtil.getConnection()){
            String sql = "INSERT INTO product VALUES(NULL,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,product.getTitle());
            ps.setDouble(2,product.getPrice());
            ps.setInt(3,product.getNum());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "添加成功";
    }


    @RequestMapping("/select")
    public String select(){
        ArrayList<Product> list = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection()){
            String sql = "SELECT * FROM product";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setTitle(rs.getString("title"));
                product.setPrice(rs.getDouble("price"));
                product.setNum(rs.getInt("num"));
                list.add(product);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list.toString();
    }
}
